//处方开具
import React, { useState, useEffect } from "react";
import {
  DatePicker,
  Form,
  Dropdown,
  Table,
  Modal,
  Image,
  Input,
  message,
  InputNumber,
  Popconfirm,
  Button,
} from "antd";
import "../../../styles/prescriptionIssuance.css";
import { fetchAllDoctor, fetchRecipelAdd } from "../../../request/hytApi";
import { DeleteTwoTone, SearchOutlined } from "@ant-design/icons";

const PrescriptionIssuance = () => {
  const [delItem, setdelItem] = useState([]); // 删除的id数据
  const [doctorName, setDoctorName] = useState("赵阳"); //选中的医生
  const [doctorNameList, setDoctorNameList] = useState([]); //医生列表
  const [doctorNameListMenu, setDoctorNameListMenu] = useState([]); //医生列表名字
  const [nameFilter, setNameFilter] = useState(""); // 名字过滤
  const [visible, setVisible] = useState(false); // 控制模态框显示的状态
  const [form] = Form.useForm(); // 表单实例
  const [dataSource, setDataSource] = useState([]); // .初始化数据源
  const [totalPrice, setTotalPrice] = useState(0); // 初始化总价

  // .每次数据变化时重新计算总价
  useEffect(() => {
    const sum = dataSource.reduce((sum, item) => {
      return sum + item.price * item.quantity;
    }, 0);
    setTotalPrice(sum);
  }, [dataSource]); // 只有 dataSource 变化时会执行

  // .请求药品数据
  useEffect(() => {
    fetchAllDoctorFn();
  }, []);

  // .获取医生列表
  const fetchAllDoctorFn = async () => {
    const res = await fetchAllDoctor();
    if (res.code === 1) {
      setDoctorNameList(res.data);
      const doctorName = res.data.map((item) => item.name);
      setDoctorNameListMenu(doctorName);
    }
  };

  // .处理删除
  const handleDelete = (key) => {
    const newDataSource = dataSource.filter((item) => item.key !== key);
    setDataSource(newDataSource); // 更新状态
  };
  // .处理输入框的变化
  const handleNameChange = (e) => {
    setNameFilter(e.target.value);
  };

  // .查询按钮点击事件
  const handleSearch = async () => {
    const setDataSourceCopy = [...dataSource];
    if (nameFilter) {
      const filteredData = dataSource.filter((item) =>
        item.name.includes(nameFilter)
      );

      setDataSource(filteredData); // 更新显示的数据
      message.success("查询成功");
    } else {
      setDataSource(setDataSourceCopy); // 更新显示的数据
    }
  };

  // .处理批量删除
  const handleAllDel = async () => {
    const str = JSON.stringify(delItem);
    console.log("🚀 ~批量删除id:", str);
    const newDataSource = dataSource.filter(
      (item) => !delItem.includes(item.id)
    );
    setDataSource(newDataSource); // 更新状态
  };

  //.复选框事件
  const rowSelection = {
    onChange: (selectedRowKeys, selectedRows) => {
      // selectedRowKeys 是勾选的行的 key
      // selectedRows 是勾选的行的完整数据
      console.log("Selected Row Keys: ", selectedRows);
      // 获取 selectedRows 中每一项的 id
      const selectedIds = selectedRows.map((row) => row.id); // 假设每一行有 id 字段
      setdelItem(selectedIds);
      // 使用展开运算符将 selectedIds 合并到 delItem 中
    },
  };

  // .创建下拉菜单
  const items = doctorNameListMenu.map((item, index) => ({
    key: String(index + 1), // 你可以根据需要修改 key
    label: item, // 医生名字作为 label
  }));

  // .点击菜单项时更新 doctorName
  const handleMenuClick = (e) => {
    // 通过 e.key 找到对应的医生名字
    const selectedDoctor = doctorNameListMenu[parseInt(e.key) - 1];
    setDoctorName(selectedDoctor); // 更新医生名字
    message.success(`已选择医生：${selectedDoctor}`);
  };

  // .控制添加药品按钮的点击事件
  const addList = () => {
    setVisible(true); // 显示模态框
  };

  // .处理模态框的确认按钮点击事件
  const handleOk = async () => {
    try {
      // 验证表单并获取表单数据
      const values = await form.validateFields();
      const timestamp = Date.now();
      // 格式化expiryDate字段
      values.expiration = values.expiration.format("YYYY-MM-DD");
      const formData = {
        ...values,
        key: timestamp, // 新增 key 属性
        image: "path/to/image1.jpg",
      };
      setDataSource([...dataSource, formData]);
      setVisible(false); // 关闭模态框
      form.resetFields(); // 重置表单
    } catch (error) {
      console.log("Form Validation Failed:", error);
    }
  };

  // .处理模态框的取消按钮点击事件
  const handleCancel = () => {
    setVisible(false); // 关闭模态框
  };

  //.开具处方
  const handleOpen = async () => {
    const dataSourceObj = dataSource.map((item) => {
      return {
        dtugname: item.name,
        type: item.specification,
        strattime: item.expiration,
        endtime: item.expiration,
        price: item.price,
        count: item.quantity,
        img: item.image,
        other: item.note,
      };
    });
    const dataSourceStr = JSON.stringify(dataSourceObj).replace(/\"/g, "'");
    console.log("dataSource", dataSourceStr);
    const id = doctorNameList.find((item) => item.name === doctorName).id;
    console.log("🚀 ~ handleOpen ~ id:", id);
    const res = await fetchRecipelAdd({
      doctorid: id,
      recipel: dataSourceStr,
      price: 11,
    });
    console.log(res);
  };

  // .列定义
  const columns = [
    {
      title: "药品名称",
      dataIndex: "name",
      key: "name",
      style: { color: "gray" },
    },
    {
      title: "药品图片",
      dataIndex: "image",
      key: "image",
      render: (image) => <Image width={48} src={image} />,
    },
    {
      title: "药品规格",
      dataIndex: "specification",
      key: "specification",
    },
    {
      title: "药品单价",
      dataIndex: "price",
      key: "price",
    },
    {
      title: "药品数量",
      dataIndex: "quantity",
      key: "quantity",
    },
    {
      title: "有效期",
      dataIndex: "expiration",
      key: "expiration",
    },
    {
      title: "用药备注",
      dataIndex: "note",
      key: "note",
    },
    {
      title: "操作",
      key: "action",
      render: (_, record) => (
        <Popconfirm
          title="确定要删除吗？"
          onConfirm={() => handleDelete(record.key)} // 删除药品
        >
          <Button type="link" danger icon={<DeleteTwoTone />} />
        </Popconfirm>
      ),
    },
  ];

  return (
    <div>
      <div
        style={{ marginBottom: "15px", display: "flex", alignItems: "center" }}
      >
        <Input
          placeholder="输入药品/器材/疫苗名称"
          style={{ width: 250, marginRight: 10 }}
          value={nameFilter}
          onChange={handleNameChange} // 绑定输入框的变化
        />

        <Button
          style={{ marginRight: "auto" }}
          type="primary"
          onClick={handleSearch}
          icon={<SearchOutlined />}
        >
          查询
        </Button>
        <Button
          style={{ marginRight: "10px" }}
          type="primary"
          onClick={addList}
        >
          添加药品
        </Button>

        <Button onClick={handleAllDel}>删除选中</Button>
      </div>
      <Table
        columns={columns}
        dataSource={dataSource}
        rowKey="key"
        pagination={false}
        rowSelection={rowSelection} // 配置复选框
      />
      <div
        style={{
          display: "flex",
          justifyContent: "flex-end",
          marginTop: "15px",
          alignItems: "center",
        }}
      >
        <span style={{ marginRight: "20px" }}>总价：{totalPrice}</span>{" "}
        <div style={{ marginRight: "20px" }}>
          <span>医生签名 : </span>
          <Dropdown
            menu={{
              items,
              onClick: handleMenuClick, // 设置点击菜单项的事件处理函数
            }}
            placement="bottomLeft"
          >
            <Button style={{ height: "25px", fontSize: "12px" }}>
              {doctorName}
            </Button>
          </Dropdown>
        </div>
        <Button
          onClick={handleOpen}
          style={{ marginRight: "20px" }}
          type="primary"
        >
          开具处方
        </Button>
      </div>
      <Modal
        title="添加药品"
        open={visible}
        onOk={handleOk}
        onCancel={handleCancel}
        okText="提交"
        cancelText="取消"
        width={600}
      >
        <Form
          form={form}
          layout="vertical"
          name="add_medicine"
          initialValues={{ remember: true }}
        >
          <Form.Item
            label="药品名称"
            name="name"
            rules={[{ required: true, message: "请输入药品名称!" }]}
          >
            <Input placeholder="请输入药品名称" />
          </Form.Item>

          <Form.Item
            label="药品规格"
            name="specification"
            rules={[{ required: true, message: "请输入药品规格!" }]}
          >
            <Input placeholder="请输入药品规格" />
          </Form.Item>

          <Form.Item
            label="药品单价"
            name="price"
            rules={[{ required: true, message: "请输入药品单价!" }]}
          >
            <InputNumber
              min={0}
              step={0.01}
              style={{ width: "100%" }}
              placeholder="请输入药品单价"
            />
          </Form.Item>

          <Form.Item
            label="药品数量"
            name="quantity"
            rules={[{ required: true, message: "请输入药品数量!" }]}
          >
            <InputNumber
              min={1}
              style={{ width: "100%" }}
              placeholder="请输入药品数量"
            />
          </Form.Item>

          <Form.Item
            label="有效期"
            name="expiration"
            rules={[{ required: true, message: "请选择药品有效期!" }]}
          >
            <DatePicker style={{ width: "100%" }} />
          </Form.Item>

          <Form.Item label="用量备注" name="note">
            <Input.TextArea rows={4} placeholder="请输入用量备注" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default PrescriptionIssuance;
